<?php

/**
 * @author .W<jeakry88@sina.com>
 * @see mysql pdo connection
 * @see 主要针对单表进行操作，多表操作请直接pdo对象操作Sql语句
 * @version 1.0.1 utf8
 * @copyright  © 2015 Huxun. All Rights Reserved
 * 
 */
class MysqlPDO {
	
	/**
	 *
	 * @see 默认构造函数
	 * @param string $tbl
	 *        	表名
	 * @param array $fields
	 *        	默认字段名数组
	 * @throws Exception 连接数据量异常
	 */
	protected function __construct($tbl, $fields) {
		$this->pdo = new PDO ( 'mysql:host=localhost;dbname=garden_system', 'root', 'root' );
		$this->pdo->exec ( 'SET NAMES utf8' );
		if (! $this->pdo)
			throw new Exception ( '数据库连接错误！' );
		$this->tbl = $tbl;
		$this->fields = $fields;
	}
	
	/**
	 *
	 * @see 默认析构函数
	 */
	function __destruct() {
		unset ( $this->pdo );
	}
	
	/**
	 *
	 * @see 返回PDO连接对象
	 */
	public function get_pdo() {
		return $this->pdo;
	}
	
	/**
	 *
	 * @see 获取表名
	 * @return string
	 */
	public function get_table_name() {
		return $this->tbl;
	}
	/**
	 *
	 * @param array $fields
	 *        	demo array('fieldname1','fieldname2','fieldname3')
	 */
	public function set_fields($fields) {
		$this->fields = $fields;
	}
	/**
	 *
	 * @see 按传入顺序自动生成排序字段
	 *
	 * @param array $orders
	 *        	demo array('fieldname'=>‘desc’,'fieldname'=>'asc')
	 */
	public function set_orders($orders) {
		$this->orders = $orders;
	}
	
	/**
	 *
	 * @param array $records
	 *        	demo array('fieldname1'=>'fieldvalue1','fieldname2'=>'fieldvalue2')
	 * @return boolean 或自增长id
	 */
	public function insert($records) {
		if (! is_array ( $records ) || count ( $records ) === 0)
			return false;
		$flds = '';
		$val = '';
		foreach ( $records as $fld => $v ) {
			$flds .= "$fld,";
			$val .= "'$v',";
		}
		$flds = mb_substr ( $flds, 0, - 1, 'utf-8' );
		$val = mb_substr ( $val, 0, - 1, 'utf-8' );
		$sql = "insert into  $this->tbl ($flds) values ($val) ";
		fb ( $sql );
		$ret = $this->pdo->exec ( $sql );
		if ($ret === false)
			return false;
		if (is_int ( $ret ) && $ret > 0) {
			$id = $this->pdo->lastInsertId ();
			return $id;
		}
		return false;
	}
	
	/**
	 *
	 * @see 按条件物理删除数据
	 * @param array $mixed
	 *        	array('fieldname1'=>'value1','fieldname2'=>array('value2','value3','value4'))
	 * @return boolean
	 */
	public function article($mixed) {
		$where = self::create_where ( $mixed );
		if (is_bool ( $where ))
			return false;
		
		$sql = "delete from  $this->tbl where $where ";
		// $sql = iconv ( 'utf-8', 'gb2312', $sql );
		$ret = $this->pdo->exec ( sql );
		if ($ret === false)
			return false; // 操作失败
		else
			return $ret > 0;
	}
	
	/**
	 *
	 * @see gaowei
	 * @see 招数组格式生成Sql条件字符串，默认按全文匹配和and模式拼接，支持字段用in查询
	 * @param array $mixed
	 *        	array('fieldname1'=>'value1','fieldname2'=>array('value2','value3','value4'))
	 */
	protected function create_where($mixed) {
		if (is_array ( $mixed ) && count ( $mixed ) !== 0) {
			$where = '';
			foreach ( $mixed as $field => $value ) {
				$item = '';
				if (is_array ( $value )) {
					if (count ( $value ) === 0)
						continue;
					$item .= " $field in (";
					foreach ( $value as $v ) {
						$v = str_replace ( '\'', "", $v );
						$item .= "'$v',";
					}
					$item = mb_substr ( $item, 0, - 1, 'utf-8' );
					$item .= ') ';
				} else {
					$j = ( string ) $field;
					$v = str_replace ( '\'', "", $value );
					if (false === strpos ( $value, '[code]' ))
						$item .= "$field='$value' ";
					else
						$item .= "$field " . str_replace ( '[code]', '', $value ); // SQL代码和函数
				}
				$where .= $item . 'and ';
			}
			$where = mb_substr ( $where, 0, - 4, 'utf-8' );
			return $where;
		} else {
			return false;
		}
	}
	/**
	 *
	 * @see 动态创建排序字段
	 * @param null|array $order        	
	 * @return string
	 */
	protected function create_order($order) {
		if (is_array ( $order ) && count ( $order ) !== 0) {
			
			$orderStr = "";
			foreach ( $order as $fld => $oby ) {
				$orderStr .= " $fld $oby,";
			}
			$orderStr = mb_substr ( $orderStr, 0, - 1, 'utf-8' );
			return $orderStr;
		}
		return ' ';
	}
	/**
	 *
	 * @see 动态创建排序字段
	 * @param null|array $order        	
	 * @return string
	 */
	protected function create_field_update($fldvalue) {
		$where = "";
		foreach ( $fldvalue as $field => $value ) {
			if (false === strpos ( $value, '[code]' ))
				$where .= "$field='$value' ,";
			else
				$where .= "$field=" . str_replace ( '[code]', '', $value ) . " ,";
			// $where .= $item . 'and ';
		}
		$where = mb_substr ( $where, 0, - 1, 'utf-8' );
		return $where;
	}
	/**
	 *
	 * @see 按条件伪删除数据
	 * @param array $mixed
	 *        	array('fieldname1'=>'value1','fieldname2'=>array('value2','value3','value4'))
	 * @return boolean
	 */
	public function delete_records_bogus($mixed) {
		$where = self::create_where ( $mixed );
		if (is_bool ( $where ))
			return false;
		$sql = "update  $this->tbl  set deleted = 1 where  $where";
		$ret = $this->pdo->exec ( $sql );
		sys_debug_log ( $sql );
		if (false === $ret)
			return false;
		return $ret >= 0;
	}
	/**
	 *
	 * @see 按条件删除数据
	 * @param array $mixed
	 *        	array('fieldname1'=>'value1','fieldname2'=>array('value2','value3','value4'))
	 * @return boolean
	 */
	public function delete_records($mixed) {
		$where = self::create_where ( $mixed );
		if (is_bool ( $where ))
			return false;
		$sql = "delete from  $this->tbl  where  $where";
		$ret = $this->pdo->exec ( $sql );
		if (false === $ret)
			return false;
		return $ret >= 0;
	}
	/**
	 *
	 * @see 更新表数据记录
	 * @param array $fldvalue
	 *        	字段键值对
	 *        	array(fieldname=>fieldvalue,...)
	 * @param array $mixed
	 *        	条件
	 *        	=array(array(),array()...)
	 * @return boolean
	 */
	public function update($fldvalue, $mixed) {
		if (! is_array ( $fldvalue ) || count ( $fldvalue ) === 0)
			return false;
		$where = '';
		if (is_array ( $mixed ) && count ( $mixed ) !== 0) {
			$where = self::create_where ( $mixed );
		} else
			return false;
		$flds = self::create_field_update ( $fldvalue );
		$sql = " update $this->tbl set $flds where $where ";
		fb ( $sql );
		$ret = $this->pdo->exec ( $sql );
		if (false === $ret)
			return false;
		return (( int ) $ret >= 0);
	}
	
	/**
	 *
	 * @see 查询单表数据列表，只支持全文匹配和in模式,
	 * @param array $mixed
	 *        	条件 demo array('fldname'=>'1',fldid=>array('1','2'))
	 * @param number $page
	 *        	第几页
	 * @param number $count
	 *        	每页页数
	 * @param array $field
	 *        	要查的字段数组 默认查询构造函数中定义的字段
	 * @param array $order
	 *        	排序字段 默认按id倒序排列
	 * @return boolean|array
	 */
	public function get_records($mixed, $page = 1, $count = 10, $field = null, $order = null) {
		if (! is_numeric ( $page ) || ! is_numeric ( $count ))
			return false;
		$where = '';
		if (empty ( $mixed )) // 无条件时，默认查所有
			$where = '1=1 ';
		else if (is_array ( $mixed ) && count ( $mixed ) !== 0) {
			$where = self::create_where ( $mixed );
		} else {
			return false;
		}
		if ($field === null || ! is_array ( $field ) || count ( $field ) === 0) {
			$field = $this->fields; // 未传字段是查询默认字段
		}
		if ($order == null || ! is_array ( $order ) || count ( $order ) === 0) {
			$order = array (
					"id" => "desc" 
			);
		}
		$orderStr = self::create_order ( $order );
		$page -= 0;
		$count -= 0;
		$sql = "";
		if (0 === $page || - 1 === $page) {
			// 查询所有
			$sql = "select " . implode ( ',', $field ) . " from $this->tbl where $where order by $orderStr";
		} else {
			if (1 === $page) {
				// 查询前几行
				$sql = "select " . implode ( ',', $field ) . " from  $this->tbl where $where order by $orderStr limit $count";
			} else {
				// 分页
				$startIndex = ($page - 1) * $count;
				$sql = "select " . implode ( ',', $field ) . " from $this->tbl where $where order by $orderStr limit $startIndex , $count";
			}
		}
		fb ( $sql );
		$ret = $this->pdo->query ( $sql );
		if ($ret === false)
			return false;
		$rows = $ret->fetchAll ();
		return $rows;
	}
	
	/**
	 *
	 * @see 按条件查询数据的记录数
	 * @param array $mixed
	 *        	条件 demo array('fldname'=>'1',fldid=>array('1','2'))
	 * @return boolean|int
	 */
	public function get_record_count($mixed) {
		$where = '';
		if (empty ( $mixed ))
			$where = '1=1 ';
		else if (is_array ( $mixed ) && count ( $mixed ) !== 0) {
			$where = self::create_where ( $mixed );
		} else
			return false;
		$sql = 'select  count(1) as sums from ' . $this->tbl . ' ' . 'where ' . $where;
		$ret = $this->pdo->query ( $sql );
		if (false === $ret)
			return false;
		$rsc = $ret->fetchColumn ();
		return $rsc;
	}
	
	/**
	 *
	 * @see 通过pdo直接执行sql语句，针对有返回结果类型的语句
	 * @param unknown $sql        	
	 * @return boolean|mixed
	 */
	public function query($sql) {
		if (! is_string ( $sql ))
			return false;
			// $sql = iconv ( 'utf-8', 'gb2312', $sql );
		$ret = $this->pdo->query ( $sql );
		if ($ret === false)
			return false;
		$rsc = $ret->fetchAll ();
		return $rsc;
	}
}

?>